package com.google.project.client.ProjectManager;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.google.gwt.cell.client.CheckboxCell;
import com.google.gwt.cell.client.ClickableTextCell;
import com.google.gwt.cell.client.FieldUpdater;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.DefaultSelectionEventManager;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.MultiSelectionModel;
import com.google.project.client.Service.ProjTaskService;
import com.google.project.client.Service.ProjTaskServiceAsync;
import com.google.project.client.Service.ProjectService;
import com.google.project.client.Service.ProjectServiceAsync;
import com.google.project.client.Service.TaskConstrainService;
import com.google.project.client.Service.TaskConstrainServiceAsync;
import com.google.project.shared.CommonFuntion;
import com.google.project.shared.ProjectDTO;
import com.google.project.shared.ProjectTaskDTO;
import com.google.project.shared.TaskConstrainDTO;
import com.google.gwt.user.client.ui.Label;


public class PMProjectTaskStep extends Composite {

	private static final Binder binder = GWT.create(Binder.class);
	@UiField(provided=true) CellTable<TaskConstrainDTO> ctbTaskConstrain = new CellTable<TaskConstrainDTO>();
	@UiField Button btnCreateConstrain;
	@UiField ListBox cboTaskConstrain;
	@UiField ListBox cboConstrainType;
	@UiField Button button;
	@UiField Button button_1;
	@UiField Label lblInfo;
	@UiField Label lblProject;
	interface Binder extends UiBinder<Widget, PMProjectTaskStep> {
	}
	final MultiSelectionModel<TaskConstrainDTO> selectionModel = new MultiSelectionModel<TaskConstrainDTO>();
	//_____________________________Common variable_____________________________
	   private  String  projectID;
	   private ProjectTaskDTO currTask= new ProjectTaskDTO();
	   private int type ;
	   private final TaskConstrainServiceAsync taskConstrainService = GWT.create(TaskConstrainService.class);
	   private final ProjectServiceAsync pmProject = GWT.create(ProjectService.class);
	   private final ProjTaskServiceAsync taskService = GWT.create(ProjTaskService.class);
	//End__________________________Common variable_____________________________
	   
	//________________________________Contructor_______________________________
		public PMProjectTaskStep() {
			initWidget(binder.createAndBindUi(this));
		}
	   //contructor update task
		public PMProjectTaskStep(ProjectTaskDTO task,String projectID,int type) {
			this.type = type;
			// TODO Auto-generated constructor stub
			initWidget(binder.createAndBindUi(this));
			//this.taskKey =taskKey;
			currTask=task;
			lblInfo.setText("Công việc : "+currTask.getTaskName());
		//	lblProject.setText("Dự án : "+currTask.getProject().getProjectName());
			this.projectID = projectID;
			pmProject.getProjectById(projectID, new AsyncCallback<ProjectDTO>() {
				
				@Override
				public void onSuccess(ProjectDTO result) {
					// TODO Auto-generated method stub
					
					lblProject.setText("Dự án : "+result.getProjectName());
				}
				
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}
			});
			loadDataForDisplay();
		}
	//End_____________________________Contructor_______________________________
		
		
	//_____________________________Common function_____________________________
		//lay ve danh sach tat ca cac rang buoc cua task va cac rang buoc gian tiep den no
		String getAllDepenOftask(String sub,List<ProjectTaskDTO> taskList)
		{   
			
			String newSub = "";
			for(int i =0;i<taskList.size();i++)
			{   
				String preData ="";
				if(taskList.get(i).getDependent()!=null&&!taskList.get(i).getDependent().equalsIgnoreCase(""))
				{
				 preData =  taskList.get(i).getDependent().substring(0, taskList.get(i).getDependent().indexOf("|"));
				}
				if(CommonFuntion.checkContain(sub,taskList.get(i).getTaskId()+"")&&preData!=null&&preData.length()>0)
				{
					
					newSub = newSub+","+preData;
				}
				
			}
			if(newSub.length()>0)
			{
				//sub+=newSub;
				sub += getAllDepenOftask(newSub,taskList);
				
			}
			
			return sub;
		}
		
		
		String getAllAfterOftask(String after,List<ProjectTaskDTO> taskList)
		{   
			
			String newAfter = "";
			for(int i =0;i<taskList.size();i++)
			{   
				String afterData ="";
				
				if(taskList.get(i).getDependent()!=null&&!taskList.get(i).getDependent().equalsIgnoreCase(""))
				{
					
					 afterData = taskList.get(i).getDependent().substring(taskList.get(i).getDependent().indexOf("|"));
					if(afterData.length()>1)
					{
						afterData=afterData.substring(1);
					}
					else
					{
						afterData="";
					}
				}
				
				if(CommonFuntion.checkContain(after,taskList.get(i).getTaskId()+"")&&afterData!=null&&afterData.length()>0)
				{
					newAfter = newAfter+","+afterData;
				}
				
			}
			if(newAfter.length()>0)
			{
				//sub+=newSub;
				after += getAllAfterOftask(newAfter,taskList);
				
			}
			
			return after;
		}
		public void loadCeltable(List<TaskConstrainDTO> constrainList)
		{
			
         
			ctbTaskConstrain.setSelectionModel(selectionModel,
			    DefaultSelectionEventManager.<TaskConstrainDTO> createCheckboxManager());
			Column<TaskConstrainDTO, Boolean> checkColumn = new Column<TaskConstrainDTO, Boolean>(
			    new CheckboxCell(true, false)) {
			  @Override
			  public Boolean getValue(TaskConstrainDTO object) {
			    // Get the value from the selection model.
			    return selectionModel.isSelected(object);
			  }
			};

			TextColumn<TaskConstrainDTO> constrainTaskColumn = new TextColumn<TaskConstrainDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(TaskConstrainDTO constrain) {
					
					return constrain.getConstrainTaskName();
				}
			};
			
			TextColumn<TaskConstrainDTO> stt = new TextColumn<TaskConstrainDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(TaskConstrainDTO constrain) {
					
					return constrain.getIndex();
				}
			};
			
			TextColumn<TaskConstrainDTO> constrainTypeColumn = new TextColumn<TaskConstrainDTO>() {
				@SuppressWarnings("deprecation")
				@Override
				public String getValue(TaskConstrainDTO constrain) {
					String temp="";
					if(constrain.getConstrainType()==1)
					{
						temp ="Cần hoàn thành";
					}
					return temp;
				}
			};
		   
			Column<TaskConstrainDTO, String> deleteColumn = new Column<TaskConstrainDTO, String>(
					new ClickableTextCell()) {
				@Override
				public String getValue(TaskConstrainDTO object) {
					return "delete";
				}
			};

			deleteColumn
					.setFieldUpdater(new FieldUpdater<TaskConstrainDTO, String>() {

						@Override
						public void update(int index, TaskConstrainDTO constrain,
								String value) {
							// PMEntrypoint.get().PMProjectTask(task.getId(),projectID);
							if (Window.confirm("Bạn có muốn xóa không")) {
								taskConstrainService.deleteConstrain(constrain.getId(), new AsyncCallback<Void>() {
									
									@Override
									public void onSuccess(Void result) {
										Window.alert("Xóa thành công");
										PMEntrypoint.get().PMProjectTaskStep2( currTask,projectID,type);
									}
									
									@Override
									public void onFailure(Throwable caught) {
										// TODO Auto-generated method stub
										
									}
								});

							}

						}

					});
			ctbTaskConstrain.addColumn(checkColumn, SafeHtmlUtils.fromSafeConstant("<br/>"));
			ctbTaskConstrain.addColumn(stt, "STT");
			
			ctbTaskConstrain.setColumnWidth(checkColumn, 40, Unit.PX);
			ctbTaskConstrain.addColumn(constrainTaskColumn, "Tên công việc");
			ctbTaskConstrain.addColumn(constrainTypeColumn, "Loại ràng buộc");
			
			//ctbTaskConstrain.addColumn(deleteColumn,"");
			ListDataProvider<TaskConstrainDTO> dataProvider = new ListDataProvider<TaskConstrainDTO>();

			// Connect the table to the data provider.
			dataProvider.addDataDisplay(ctbTaskConstrain);
			int count =1;
			List<TaskConstrainDTO> list = dataProvider.getList();
			for (TaskConstrainDTO costrain : constrainList) {
				costrain.setIndex(count+"");
				list.add(costrain);
			}
		
		}
		void loadDataForDisplay()
		{
			//lay ve list task
			pmProject.getListTask(projectID, new AsyncCallback<List<ProjectTaskDTO>>() {
				
				@Override
				public void onSuccess(final List<ProjectTaskDTO> taskList) {
					// TODO Auto-generated method stub
			
					//lay ve task hien tai
			taskService.getTaskById(currTask.getId(), new AsyncCallback<ProjectTaskDTO>() {
				
				@Override
				public void onSuccess(ProjectTaskDTO result) {
					// TODO Auto-generated method stub
					currTask=result;
				
					List<ProjectTaskDTO> listForCbo=new ArrayList<ProjectTaskDTO>();
					cboTaskConstrain.addItem("Lựa chọn", "0");
					if(currTask!=null&&taskList.size()>0&&currTask.getGroup()==0 &&currTask.getIsMile()==0 )
					{
						//kiem tra task hien tai co rang buoc chua
						if(currTask.getDependent()!=null&&currTask.getDependent().length()>1)
						{
							//cat lay pre
							String preData =  currTask.getDependent().substring(0, currTask.getDependent().indexOf("|"));
							//cat lay after data
							String afterData = currTask.getDependent().substring(currTask.getDependent().indexOf("|"));
						
							if(afterData.length()>1)
							{
								afterData=afterData.substring(1);
							}
							else
							{
								afterData="";
							}	
						
						
							//kiem tra ko lay task pre
							if(preData!=null&&preData.length()>0)
							{
							
							String sub = getAllDepenOftask(preData, taskList);
							//Window.alert("Pre:"+sub);
							for(int i =0;i<taskList.size();i++)
							{

								if(!CommonFuntion.checkContain(sub,taskList.get(i).getTaskId()+"") &&taskList.get(i).getTaskId()!=currTask.getTaskId())
								{
									//Window.alert(taskList.get(i).getTaskId()+ "  curtask:"+result.getTaskId());
									listForCbo.add(taskList.get(i));
								//cboTaskConstrain.addItem(taskList.get(i).getTaskName(), ""+taskList.get(i).getTaskId());
								}
							}
							}
							else
							{
								//Window.alert("Vao day ne1");
								for(int i =0;i<taskList.size();i++)
								{
									if(taskList.get(i).getTaskId()!=currTask.getTaskId())
									{
									
										listForCbo.add(taskList.get(i));
									
									}
								}
							}
							
							//kiem tra ko lay task after
							if(listForCbo!=null&&listForCbo.size()>0)
							{
								
								if(afterData!=null&&afterData.length()>0)
								{

								String listAfter = getAllAfterOftask(afterData, taskList);
								//Window.alert("After:"+listAfter);
								for(int i =0;i<listForCbo.size();i++)
								{

									if(!CommonFuntion.checkContain(listAfter,listForCbo.get(i).getTaskId()+"") &&listForCbo.get(i).getTaskId()!=currTask.getTaskId()&&listForCbo.get(i).getGroup()==0&&listForCbo.get(i).getIsMile()==0)
									{
										//listForCbo.add(taskList.get(i));
										if(listForCbo.get(i).getStatus()!=3&&taskList.get(i).getStatus()!=2)
										{
											if(listForCbo.get(i).getDueDate()<currTask.getStartDate())
											{
												cboTaskConstrain.addItem(listForCbo.get(i).getTaskName(), ""+listForCbo.get(i).getTaskId());
											}
										}
										}
								}
								}
								else
								{
									
									for(int i =0;i<listForCbo.size();i++)
									{
										if(listForCbo.get(i).getTaskId()!=currTask.getTaskId()&&listForCbo.get(i).getGroup()==0&&listForCbo.get(i).getIsMile()==0)
										{
											//listForCbo.add(taskList.get(i));
											if(listForCbo.get(i).getStatus()!=3&&taskList.get(i).getStatus()!=2)
											{
												if(listForCbo.get(i).getDueDate()<currTask.getStartDate())
												{
													cboTaskConstrain.addItem(listForCbo.get(i).getTaskName(), ""+listForCbo.get(i).getTaskId());
												}
											}
											}
									}
								}
							}
							
							
							
							
						}
						else
						{
							
							for(int i =0;i<taskList.size();i++)
							{
								if(taskList.get(i).getTaskId()!=currTask.getTaskId() && taskList.get(i).getGroup()==0 && taskList.get(i).getIsMile()==0)
								{
									//listForCbo.add(taskList.get(i));
									if(taskList.get(i).getStatus()!=3&&taskList.get(i).getStatus()!=2)
									{
										if(taskList.get(i).getDueDate()<currTask.getStartDate())
										{
											cboTaskConstrain.addItem(taskList.get(i).getTaskName(), ""+taskList.get(i).getTaskId());
										}
									}
									}
							}
						}
						
					}
				}
				
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					//Window.alert("Có lỗi xảy ra");
				}
			});
						
				}
					
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					Window.alert("Có lỗi xảy ra");
				}
			});
			cboConstrainType.addItem("Cần hoàn thành","1");
			cboConstrainType.setSelectedIndex(0);
		
			taskService.getListConstrain(currTask.getId(), new AsyncCallback<List<TaskConstrainDTO>>() {
				
				@Override
				public void onSuccess(List<TaskConstrainDTO> result) {
					// TODO Auto-generated method stub
					loadCeltable(result);
				}
				
				@Override
				public void onFailure(Throwable caught) {
					// TODO Auto-generated method stub
					
				}
			});
		}
				
	//End__________________________Common function_____________________________
	
	//___________________________________Event_________________________________
		
		@UiHandler("btnCreateConstrain")
		void onBtnCreateConstrainClick(ClickEvent event) {
			TaskConstrainDTO data = new TaskConstrainDTO();
			data.setConstrainTaskName(cboTaskConstrain.getItemText(cboTaskConstrain.getSelectedIndex()));
			data.setConstrainTaskId(Integer.parseInt(cboTaskConstrain.getValue(cboTaskConstrain.getSelectedIndex())));
		    data.setConstrainType(Integer.parseInt(cboConstrainType.getValue(cboConstrainType.getSelectedIndex())));
		    if(data.getConstrainTaskId()!=0)
		    {
			    taskConstrainService.createContrain(data, currTask.getId(), new AsyncCallback<TaskConstrainDTO>() {
					
					@Override
					public void onSuccess(final TaskConstrainDTO constrain) {
						// TODO Auto-generated method stub
						Window.alert("Tạo thành công!");
						PMEntrypoint.get().PMProjectTaskStep2( currTask,projectID,type);

						
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						Window.alert("Tạo thất bại!");
					}
				});
		    }
		    else
		    {
		    	Window.alert("Bạn phải chọn công việc liên quan ");
		    }

		}
		
		
		@UiHandler("button")
		void onButtonClick(ClickEvent event) {
			if(type==0)
			{
			PMEntrypoint.get().PMCreateProjectPlan(projectID);
			}
			else
			{
				PMEntrypoint.get().PMTaskDetail(currTask);
			}
		}
		@UiHandler("button_1")
		void onButton_1Click(ClickEvent event) {
			
			Set<TaskConstrainDTO> listChecked = selectionModel.getSelectedSet();
			List<TaskConstrainDTO> list = new ArrayList<TaskConstrainDTO>();
			for (TaskConstrainDTO specializeDTO : listChecked) {
				list.add(specializeDTO);
			}
			if(list!=null&&list.size()>0)
			{
			if (Window.confirm("Bạn có muốn xóa ràng buộc không?")) {
				taskConstrainService.deleteListConstrain(list, new AsyncCallback<Void>() {
					
					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub
						Window.confirm("Xóa thành công?");
						PMEntrypoint.get().PMProjectTaskStep2( currTask,projectID,type);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						// TODO Auto-generated method stub
						
					}
				});
			}
			
			}
			else
			{
				Window.confirm("Bạn phải chọn ràng buộc để xóa");
			}		
			selectionModel.clear();
		}
}
